﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceStack;
using System.Security.Cryptography;
using System.Text;
using YouShuCode.Models;
using YouShuCode.Utils;

namespace YouShuCode
{
    public class YouShuService : IYouShuService
    {
        private string traceSource = "SFA_YOUSHUService";
        private ILogger<YouShuService> _logger; 
        private YouShuConfig youshuOptions;

        public YouShuService(ILogger<YouShuService> logger)
        {
            _logger = logger; 
            youshuOptions = YouShu.YouShuConfig;
        }
        #region
        /// <summary>
        ///
        /// </summary>
        /// <param name="entInfo"></param>
        /// <param name="username"></param>
        /// <returns>
        ///   //case 4 (With Secondary License creditCode):
        //{
        //  "code" : "0000",
        //  "msg" : "查询成功",
        //  "orderNo" : "1803291500249810041",
        //  "data" : {
        //    "basicList" : [ {
        //      "entName" : "上海芥菜籽商务咨询有限公司徐汇分公司",
        //      "entId" : "q02b080ba34bdb321b0922d70a41ec898",
        //      "creditCode" : "91310104590414210H",
        //      "regNo" : "310104000503034",
        //      "orgCode" : "590414210",
        //      "entType" : "有限责任公司分公司（自然人投资或控股）",
        //      "frName" : "顾梅",
        //      "frPersonId" : "p_01926580b34d3e835e30c449c61afd37",
        //      "regCap" : "",
        //      "regCapCur" : "人民币",
        //      "recCap" : "",
        //      "esDate" : "2011-11-01",
        //      "openFrom" : "2011-11-01",
        //      "openTo" : "2020-10-07",
        //      "regOrg" : "徐汇区市场监督管理局",
        //      "apprDate" : "2011-11-01",
        //      "entStatus" : "在营（开业）",
        //      "canDate" : "",
        //      "revDate" : "",
        //      "address" : "华山路2088号1403-1404室",
        //      "province" : "上海",
        //      "city" : "上海市",
        //      "county" : "徐汇区",
        //      "areaCode" : "310104",
        //      "operateScope" : "商务咨询，经济信息咨询，公共关系咨询，企业管理咨询，会展服务，文化艺术交流策划，销售化妆品、日用百货，食品流通。 【依法须经批准的项目，经相关部门批准后方可开展经营活动】",
        //      "ancheYear" : "2016",
        //      "ancheDate" : "2017-06-28",
        //      "industryPhyCode" : "L",
        //      "industryPhyName" : "租赁和商务服务业",
        //      "industryCode" : "7239",
        //      "industryName" : "其他专业咨询"
        //    } ],
        //    "entHisList" : [ ]
        //  }
        //}
        /// </returns>
        #endregion

        public YoushuResponseDto EnterpriseApi(string entInfo, string username)
        {
            YoushuResponseDto responseDto = new YoushuResponseDto();
            string uID = youshuOptions.UID;
            _logger.LogInformation($"Api有数环境变量，uID：{youshuOptions.UID} EntApiID：{youshuOptions.EntApiID} PLApiID：{youshuOptions.PLApiID}");
            string apiID = youshuOptions.EntApiID;
            string privateKey = youshuOptions.PrivateKey;
            string youshuBaseUrl = youshuOptions.YouShuBaseUrl;

            string paramStr = string.Format("uid={0}&api={1}&args={{\"entInfo\":\"{2}\"}}", uID, apiID, entInfo);
            byte[] paramBytes = Encoding.UTF8.GetBytes(string.Format("{0}&key={1}", paramStr, privateKey));
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(paramBytes);
            string sign = BitConverter.ToString(output).Replace("-", "").ToLower();
            string requestUrl = string.Format("{0}?{1}&sign={2}", youshuBaseUrl, paramStr, sign);
            APIConnectionLog log = new APIConnectionLog()
            {
                ApiName = ApiName.YouShu,
                ActionType = ActionType.Get,
                ConnectStartTime = DateTime.Now,
                RequestUri = requestUrl,
                RequestData = paramStr,
                UserName = username,
                Status = APIConectionStatus.New
            };

            try
            {
                HttpClient Client = new HttpClient();
                var response = Client.GetAsync(requestUrl).Result;
                if (response != null && response.IsSuccessStatusCode)
                {
                    var res = response.Content.ReadAsStringAsync();
                    var result = res.Result;
                    log.ResponseData = res.Result;
                    log.ConnectEndTime = DateTime.Now;
                    log.Status = APIConectionStatus.Requested;
                    dynamic dynamicResult = DynamicJson.Deserialize(res.Result);
                    if (dynamicResult.code == "0000")
                    {
                        log.BusinessID = dynamicResult.data.basicList[0].entId;
                        responseDto.IsSuccess = true;
                        responseDto.ApiResponse = res.Result;
                    }
                    else
                    {
                        responseDto.IsSuccess = false;
                        responseDto.Message = dynamicResult.msg;
                        responseDto.ErrorCode = ErrorCode.YouShuCompanyNameValidationFailed;
                    }
                }
                else
                {
                    log.ConnectEndTime = DateTime.Now;
                    log.Status = APIConectionStatus.Failed;
                    responseDto.IsSuccess = false;
                    responseDto.Message = "YouShu API 查询失败";
                    responseDto.ErrorCode = ErrorCode.BussinessError;
                }
            }
            catch (Exception ex)
            {
                log.ConnectEndTime = DateTime.Now;
                log.Status = APIConectionStatus.Error;

                _logger.LogError(ex.Message, traceSource, ex);

                responseDto.IsSuccess = false;
                responseDto.Message = "YouShu API 异常";
                responseDto.ErrorCode = ErrorCode.ApplicationError;
            }
            finally
            {
                var querylog = JsonHelper.ToJson(log);
                _logger.LogInformation($"EnterpriseApi查询记录日志：{querylog}");
            }

            return responseDto;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="entNameCredit"></param>
        /// <param name="frName"></param>
        /// <param name="cid"></param>
        /// <param name="regNo"></param>
        /// <param name="username"></param>
        /// <returns>
        ///   //{
        //  "code" : "0000",
        //  "msg" : "查询成功",
        //  "orderNo" : "1803291406011470784",
        //  "data" : {
        //    "isMatch" : "YES",
        //    "matchInfo" : {
        //      "ryName" : "顾梅",
        //      "entName" : "上海芥菜籽商务咨询有限公司",
        //      "regNo" : "310118002561420",
        //      "entType" : "有限责任公司（自然人投资或控股）",
        //      "regCap" : "3.000000",
        //      "regCapCur" : "人民币",
        //      "entStatus" : "在营（开业）",
        //      "creditCode" : "9131011856306610X5"
        //    }
        //  }
        //}
        /// </returns>
        public YoushuResponseDto LegalPersonApi(string entNameCredit, string frName, string cid, string regNo, string username)
        {
            string uID = youshuOptions.UID;
            string apiID = youshuOptions.EntApiID;
            string privateKey = youshuOptions.PrivateKey;
            string youshuBaseUrl = youshuOptions.YouShuBaseUrl;

            YoushuResponseDto responseDto = new YoushuResponseDto();

            string paramStr = string.Format("uid={0}&api={1}&args={{\"entNameCredit\":\"{2}\",\"frName\":\"{3}\",\"cid\":\"{4}\",\"regNo\":\"{5}\"}}"
                , uID, apiID, entNameCredit, frName, cid.ToUpper().ToSHA256(), regNo);
            byte[] paramBytes = Encoding.UTF8.GetBytes(string.Format("{0}&key={1}", paramStr, privateKey));
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(paramBytes);
            string sign = BitConverter.ToString(output).Replace("-", "").ToLower();
            string requestUrl = string.Format("{0}?{1}&sign={2}", youshuBaseUrl, paramStr, sign);
            APIConnectionLog log = new APIConnectionLog()
            {
                ApiName = ApiName.YouShu,
                ActionType = ActionType.Get,
                ConnectStartTime = DateTime.Now,
                RequestUri = requestUrl,
                RequestData = paramStr,
                UserName = username,
                Status = APIConectionStatus.New
            };

            try
            {
                HttpClient Client = new HttpClient();
                var response = Client.GetAsync(requestUrl).Result;
                if (response != null && response.IsSuccessStatusCode)
                {
                    var res = response.Content.ReadAsStringAsync();
                    var result = res.Result;
                    log.ResponseData = res.Result;
                    log.ConnectEndTime = DateTime.Now;
                    log.Status = APIConectionStatus.Requested;
                    dynamic responseDynamic = DynamicJson.Deserialize(res.Result);
                    if (responseDynamic.code == "0000" && responseDynamic.data.isMatch == "YES")
                    {
                        log.BusinessID = responseDynamic.data.matchInfo.creditCode;
                        string entStatus = responseDynamic.data.matchInfo.entStatus;
                        if (entStatus.Contains("在营"))
                        {
                            responseDto.IsSuccess = true;
                            responseDto.ApiResponse = res.Result;
                        }
                        else
                        {
                            responseDto.IsSuccess = false;
                            responseDto.Message = BDLAlertMessage.EntStatusError;
                            responseDto.ErrorCode = ErrorCode.YouShuEntStatusFailed;
                        }
                    }
                    else
                    {
                        responseDto.IsSuccess = false;
                        responseDto.Message = responseDynamic.msg;
                        responseDto.ErrorCode = ErrorCode.YouShuLegalPersonValidationFailed;
                    }
                }
                else
                {
                    log.ConnectEndTime = DateTime.Now;
                    log.Status = APIConectionStatus.Failed;
                    responseDto.IsSuccess = false;
                    responseDto.Message = "youshu API 查询失败";
                    responseDto.ErrorCode = ErrorCode.BussinessError;
                }
            }
            catch (Exception ex)
            {
                log.ConnectEndTime = DateTime.Now;
                log.Status = APIConectionStatus.Error;
                _logger.LogError(ex.Message, traceSource, ex);
                responseDto.IsSuccess = false;
                responseDto.Message = "youshu API 异常";
                responseDto.ErrorCode = ErrorCode.ApplicationError;
            }
            finally
            {
                var querylog = JsonHelper.ToJson(log);
                _logger.LogInformation($"EnterpriseApi查询记录日志：{querylog}");
            }
            return responseDto;
        }
    }
}